package cn.nawang.ebeim.server;

import cn.nawang.ebeim.server.constants.Config;
import cn.nawang.ebeim.server.service.ZookeeperService;
import cn.nawang.ebeim.server.thread.FileUploadFolderScanner;
import cn.nawang.ebeim.server.thread.ReadFileTodoThread;
import cn.nawang.ebeim.server.thread.ReadVersionTreeTodoThread;
import cn.nawang.ebeim.server.thread.VersionTreeUploadFolderScanner;
import cn.nawang.ebeim.server.transport.HttpUploadServer;
import cn.nawang.ebeim.server.util.SystemUtil;
import cn.nawang.ebeim.server.util.ThreadPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: AppMain
 * @Description: TODO
 * @author 许炜毅
 * @date 2015年8月20日 下午1:38:26
 * @version v1.0
 */
public class AppMain {

  private static final Logger LOG = LoggerFactory.getLogger(AppMain.class);

  public static void main(String[] args) {
    new AppMain().run();
  }

  public void run() {
    LOG.info("begin start main function.");
    SystemUtil.initLog();
    // 初始化
    initServer();
    // 注册Zookeeper服务
    registerZookeeper();
    LOG.info("main function start success.");
  }

  public void initServer() {
    try {
      // 初始化接收客户端上传请求
      ThreadPoolUtil.submitTask(new HttpUploadServer());
      // 扫描版本树上传文件夹
      ThreadPoolUtil.submitTask(new VersionTreeUploadFolderScanner());
      // 扫描上传文件的文件夹
      ThreadPoolUtil.submitTask(new FileUploadFolderScanner());
      // 读版本树文件到HDFS
      ThreadPoolUtil.startUploadVersionTreeToHdfsThread();
      // 读文件到HDFS
      ThreadPoolUtil.startUploadFileToHdfsThread();

      //与Api异步通讯线程
      ThreadPoolUtil.startUploadToApiServerThread();

      /** 数据迁移 **/
      if ("true".equals(Config.IS_OPEN_DATA_TRANSFER)) {
        LOG.info("data transfer start!");
        // 读取未处理的版本树
        ThreadPoolUtil.submitTask(new ReadFileTodoThread());
        // 读取未处理的数据文件
        ThreadPoolUtil.submitTask(new ReadVersionTreeTodoThread());
        // 处理数据文件
        ThreadPoolUtil.startHandleFileTodoThread();
        // 处理版本树
        ThreadPoolUtil.startHandleVersionTreeTodoThread();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void registerZookeeper() {
    try {
      ZookeeperService.instance().register();
    } catch (Exception ex) {
      LOG.error("register zookeeper failed! {}", ex);
    }
  }

}
